package com.lej.core.webView

import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.webkit.WebView
import android.widget.FrameLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import com.alibaba.android.arouter.facade.annotation.Route
import com.lej.core.R
import com.lej.core.base.app
import com.lej.core.base.statusHeight
import com.lej.core.bus.Events
import com.lej.core.common.*
import com.lej.core.common.Params.NFT_ID
import com.lej.core.common.Params.NFT_TYPE
import com.lej.core.common.Params.NFT_TYPE_BUY
import com.lej.core.router.CRouter
import com.lej.core.utils.ToastUtils
import com.qiniu.android.utils.AsyncRun
import com.qmuiteam.qmui.util.QMUIStatusBarHelper

/**
 * 网页可以处理:
 * 点击相应控件：
 * - 拨打电话、发送短信、发送邮件
 * - 上传图片(版本兼容)
 * - 全屏播放网络视频
 * - 进度条显示
 * - 返回网页上一层、显示网页标题
 * JS交互部分：
 * - 前端代码嵌入js(缺乏灵活性)
 * - 网页自带js跳转
 * 被作为第三方浏览器打开
 */
@Route(path = CRouter.webView)
open class WebViewActivity : AppCompatActivity(), IWebPageView {
    // 进度条
    private var mProgressBar: WebProgress? = null

    // 全屏时视频加载view
    override var videoFullView: FrameLayout? = null

    // 加载视频相关
    private var mWebChromeClient: MyWebChromeClient? = null

    // 网页链接
    private var mUrl: String? = null
    private var webView: WebView? = null
    private var tvGunTitle: TextView? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (intent.getBooleanExtra(ORIENTATION_PORTRAIT, false)) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
        }
        QMUIStatusBarHelper.translucent(this)
        QMUIStatusBarHelper.setStatusBarDarkMode(this)
        setContentView(R.layout.activity_web_view)
        intentData()
        initTitle()
        mWebChromeClient = webView?.initWebView(this, this)
        webView?.handleLoadUrl(mUrl)
        getDataFromBrowser(intent)

        Events.WEB_UPDATE_TOKEN.observe(this) {
            loadJs("javascript:window.setToken(\"${PCacheInfo.userToken()}\")")
        }
    }

    private fun intentData() {
        mUrl = intent.getStringExtra(WEB_URL)
        mUrl = mUrl?.addParams()
    }

    private fun initTitle() {
        webView = findViewById(R.id.web_view)
        mProgressBar = WebProgress(this).apply {
            visibility = View.GONE
            setColor(ContextCompat.getColor(this@WebViewActivity, R.color.colorAccent))
            show()
        }
        initToolBar()
    }

    private fun initToolBar() { // 可滚动的title 使用简单 没有渐变效果，文字两旁有阴影
        val mTitleToolBar = findViewById<Toolbar>(R.id.title_tool_bar)

        val isShow = intent.getBooleanExtra(WEB_SHOW_TITLE, true)
        mTitleToolBar.isVisible = isShow
        if (!isShow) {
            QMUIStatusBarHelper.setStatusBarDarkMode(this)
        }

        mTitleToolBar.updatePadding(top = statusHeight)
        tvGunTitle = findViewById(R.id.tv_gun_title)
        setSupportActionBar(mTitleToolBar)
        val actionBar = supportActionBar
        actionBar?.setDisplayShowTitleEnabled(false)
        mTitleToolBar.overflowIcon =
            ContextCompat.getDrawable(this, R.drawable.actionbar_more)
        tvGunTitle?.postDelayed({ tvGunTitle?.isSelected = true }, 1900)

        if (app.isDebug) {// 测试使用
            tvGunTitle?.setOnLongClickListener {
                if (!TextUtils.isEmpty(mUrl)) {
                    WebTools.startActivity(this, mUrl!!)
                    return@setOnLongClickListener true
                }
                false
            }
        }
    }

//    override fun onCreateOptionsMenu(menu: Menu): Boolean {
//        menuInflater.inflate(R.menu.menu_webview, menu)
//        return true
//    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> handleFinish()// 返回键
//            R.id.actionbar_share -> { // 分享到
//                val shareText = webView!!.title + webView!!.url
//                WebTools.share(this@WebViewActivity, shareText)
//            }
            R.id.actionbar_cope -> { // 复制链接
                WebTools.copy(webView!!.url)
                ToastUtils.show("复制成功")
            }
//            R.id.actionbar_open -> { // 打开链接
//                WebTools.openLink(this@WebViewActivity, webView!!.url)
//            }
            R.id.actionbar_webview_refresh -> webView?.reload()// 刷新页面
        }
        return super.onOptionsItemSelected(item)
    }

    override fun showWebView() {
        webView?.visibility = View.VISIBLE
    }

    override fun hindWebView() {
        webView?.visibility = View.INVISIBLE
    }

    override fun fullViewAddView(view: View?) {
        val decor = window.decorView as FrameLayout
        videoFullView = FullscreenHolder(this@WebViewActivity).apply { addView(view) }
        decor.addView(videoFullView)
    }

    override fun showVideoFullView() {
        videoFullView?.visibility = View.VISIBLE
    }

    override fun hindVideoFullView() {
        videoFullView?.visibility = View.GONE
    }

    override fun startProgress(newProgress: Int) {
        mProgressBar?.setWebProgress(newProgress)
    }

    private fun setTitle(mTitle: String?) {
        tvGunTitle?.text = mTitle
    }


    /**
     * android与js交互：
     * 前端注入js代码：不能加重复的节点，不然会覆盖
     * 前端调用js代码
     */
    override fun onPageFinished(view: WebView?, url: String?) {

        if (!isNetworkConnected()) {
            mProgressBar?.hide()
        }
        loadImageClickJS()
        loadTextClickJS()
        loadCallJS()
        loadWebsiteSourceCodeJS()
    }

    /**
     * 处理是否唤起三方app
     */
    override fun isOpenThirdApp(url: String?): Boolean {
        return WebTools.handleThirdApp(this, url)
    }

    /**
     * 前端注入JS：
     * 这段js函数的功能就是，遍历所有的img节点，并添加onclick函数，函数的功能是在图片点击的时候调用本地java接口并传递url过去
     */
    private fun loadImageClickJS() {
        loadJs(
            "javascript:(function(){" +
                    "var objs = document.getElementsByTagName(\"img\");" +
                    "for(var i=0;i<objs.length;i++)" +
                    "{" +
                    "objs[i].onclick=function(){window.injectedObject.imageClick(this.getAttribute(\"src\"));}" +
                    "}" +
                    "})()"
        )
    }

    /**
     * 前端注入JS：
     * 遍历所有的 * 节点,将节点里的属性传递过去(属性自定义,用于页面跳转)
     */
    private fun loadTextClickJS() {
        loadJs(
            "javascript:(function(){" +
                    "var objs =document.getElementsByTagName(\"li\");" +
                    "for(var i=0;i<objs.length;i++)" +
                    "{" +
                    "objs[i].onclick=function(){" +
                    "window.injectedObject.textClick(this.getAttribute(\"type\"),this.getAttribute(\"item_pk\"));}" +
                    "}" +
                    "})()"
        )
    }

    /**
     * 传应用内的数据给html，方便html处理
     */
    private fun loadCallJS() { // 无参数调用
        loadJs("javascript:javacalljs()")
        // 传递参数调用
        loadJs("javascript:javacalljswithargs('" + "android传入到网页里的数据，有参" + "')")
    }

    /**
     * get website source code
     * 获取网页源码
     */
    private fun loadWebsiteSourceCodeJS() {
        loadJs("javascript:window.injectedObject.showSource(document.getElementsByTagName('html')[0].innerHTML);")
    }

    /**
     * 全屏时按返加键执行退出全屏方法
     */
    @SuppressLint("SourceLockedOrientationActivity")
    fun hideCustomView() {
        mWebChromeClient!!.onHideCustomView()
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
    }

    override val videoLoadingProgressView: View
        get() = LayoutInflater.from(this).inflate(R.layout.layout_loading_progress, null)

    override fun onReceivedTitle(view: WebView?, title: String?) {
        setTitle(title)
    }

    override fun startFileChooserForResult(intent: Intent?, requestCode: Int) {
        startActivityForResult(intent, requestCode)
    }

    /**
     * 上传图片之后的回调
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
        super.onActivityResult(requestCode, resultCode, intent)
        when (requestCode) {
            MyWebChromeClient.FILECHOOSER_RESULTCODE ->
                mWebChromeClient?.mUploadMessage(intent, resultCode)
            MyWebChromeClient.FILECHOOSER_RESULTCODE_FOR_ANDROID_5 ->
                mWebChromeClient?.mUploadMessageForAndroid5(intent, resultCode)
        }
    }

    /**
     * 使用singleTask启动模式的Activity在系统中只会存在一个实例。
     * 如果这个实例已经存在，intent就会通过onNewIntent传递到这个Activity。
     * 否则新的Activity实例被创建。
     */
    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        intentData()
        initTitle()
        webView?.handleLoadUrl(mUrl)
        if (mUrl == null) {
            getDataFromBrowser(intent)
        }
    }

    /**
     * 作为三方浏览器打开传过来的值
     * Scheme: https
     * host: www.jianshu.com
     * path: /p/1cbaf784c29c
     * url = scheme + "://" + host + path;
     */
    private fun getDataFromBrowser(intent: Intent) {
        intent.data?.let {
            kotlin.runCatching {
                val scheme = it.scheme
                val host = it.host
                val path = it.path
                val text = "Scheme: $scheme\nhost: $host\npath: $path"
                Log.e("data", text)
                val url = "$scheme://$host$path"
                webView?.loadUrl(url)
            }
        }
    }

    /**
     * 直接通过三方浏览器打开时，回退到首页
     */
    private fun handleFinish() {
        supportFinishAfterTransition()
    }

    /**
     * 4.4以上可用 evaluateJavascript 效率高
     */
    fun loadJs(jsString: String) {
        AsyncRun.runInMain { webView?.evaluateJavascript(jsString, null) }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) { //全屏播放退出全屏
            when {
                mWebChromeClient!!.inCustomView() -> {
                    hideCustomView()
                    return true
                    //返回网页上一页
                }
                webView!!.canGoBack() -> {
                    webView!!.goBack()
                    return true
                    //退出网页
                }
                else -> {
                    handleFinish()
                }
            }
        }
        return false
    }

    override fun onPause() {
        super.onPause()
        webView?.onPause()
    }

    @SuppressLint("SourceLockedOrientationActivity")
    override fun onResume() {
        super.onResume()
        webView?.onResume()
        // 支付宝网页版在打开文章详情之后,无法点击按钮下一步
        webView?.resumeTimers()
        // 设置为横屏
//        if (requestedOrientation != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
//            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
//        }
    }

    override fun onDestroy() {
        videoFullView?.removeAllViews()
        videoFullView = null
        webView.onDestroy()
        webView = null
        super.onDestroy()
    }
}